const fs = require("fs");
let source = require("./source.json");
let DataTypes = {
  integer: "number",
  number: "number",
  string: "string",
  boolean: "boolean",
  array: "Array",
  object: "object",
};

function getArrayItemsType(items) {
  if (items.items) {
    let type = getArrayItemsType(items.items);
    return `Array<${type}>`;
  } else {
    if (items.originalRef) {
      return `Array<${items.originalRef}>`;
    } else {
      return `Array<${DataTypes[items.type]}>`;
    }
  }
}
function propertyToEntity(property) {
  let content = "";
  if (property.type === "object") {
    Object.keys(property.properties).forEach((key) => {
      let value = property.properties[key];
      let required = (property.required || []).includes(key) ? "?" : "";
      let description = value.description ? `/* ${value.description} */` : "";
      if (value.type == null) {
        let valueStr = "object";
        if (value.$ref) {
          // [].at() 报错
          let arr = value.$ref.split("/");
          valueStr = arr[arr.length - 1];
        }
        content += `${key}${required}: ${valueStr}; ${description}
    `;
      } else if (value.type == "array") {
        content += `${key}${required}: ${getArrayItemsType(
          value.items
        )}; ${description}
    `;
      } else if (value.type == "object") {
        content += `${key}${required}: object; ${description}
    `;
      } else if (value.type == "file") {
        content += `${key}${required}: File; ${description}
    `;
      } else {
        content += `${key}${required}: ${DataTypes[value.type]}; ${description}
    `;
      }
    });
  }
  let title = property.title.replace(/«/g, "").replace(/»/g, "");
  return `interface ${title} {
    ${content}};


  `;
}

function genAllType() {
  let result = "";
  Object.values(source.definitions).forEach((v) => {
    if (Object.prototype.toString.call(v) === "[object Object]") {
      result += propertyToEntity(v);
    }
  });
  fs.writeFile("Entity.ts", result, function (err) {
    if (err) {
      return console.error(err);
    }
    console.log("数据写入成功！");
    fs.readFile("Entity.ts", function (err, data) {
      if (err) {
        return console.error(err);
      }
      console.log("异步读取文件数据: ");
      // data.toString()
    });
  });
}

genAllType();
